package no.gnet.edvd.web.interceptor;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

public class CacheControlFilter implements Filter {
	int expiryInSeconds = 60;
	private static Logger logger = Logger.getLogger(CacheControlFilter.class);

    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
    	logger.info("Hit for " + ((HttpServletRequest)request).getRequestURI());
        HttpServletResponse resp = (HttpServletResponse) response;
		resp.addHeader("Cache-Control", "max-age="+expiryInSeconds);
        resp.setDateHeader("Expires", System.currentTimeMillis()  + (expiryInSeconds * 1000));
        chain.doFilter(request, response);
    }

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		try {
			String exp = filterConfig.getInitParameter("expiryInSeconds");
			this.expiryInSeconds=Integer.parseInt(exp);
			logger.info("Setting expiryInSeconds to " + expiryInSeconds);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

}
